package com.shujia.spark.stream

import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}

object Demo1WordCount {
  def main(args: Array[String]): Unit = {
    /**
     * 1、创建spark环境
     */
    val conf = new SparkConf()
    conf.setMaster("local[2]") //接收数据需要一个资源，处理数据也需要一个资源
    conf.setAppName("wc")

    val sc = new SparkContext(conf)

    /**
     * 2、创建spark streaming环境
     */
    val ssc = new StreamingContext(sc, Durations.seconds(5))

    /**
     * 3、读取数据
     * nc -lk 8888
     *
     * 如果命令找不到需要安装一下啊
     * yum install nc
     *
     * DStream:底层也是RDD,每隔一段时间封装一个RDD
     */

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    /**
     * 4、统计单词的数量
     */
    val countDS: DStream[(String, Int)] = linesDS
      .flatMap(line => line.split(","))
      .map((_, 1))
      .reduceByKey((x, y) => x + y)

    //打印计算结果
    countDS.print()

    /**
     * 5、启动spark streaming任务
     */
    ssc.start()
    ssc.awaitTermination()
    ssc.stop()
  }
}
